<template>
  <div style="width: 100%;" class="card-area">
    <layout-content topTitle="查询" bottomTitle="商品列表">
      <!-- 搜索区域 -->
      <template v-slot:topCard>
        <search-view ref="searchView" @search="search" ></search-view>
      </template>
      <!-- 额外操作，在右侧 -->
      <template v-slot:extraOperation>
        <a-button class="extra-btn" type="primary" @click="handleOperationClick('add')">
          新增
        </a-button>
      </template>
      <!-- 表格区域 -->
      <template v-slot:bottomCard>
        <a-table
          ref="TableInfo"
          :columns="columns"
          rowKey="id"
          :dataSource="dataSource"
          :pagination="pagination"
          :loading="loading"
          :scroll="{ x: 1300 }"
          @change="handleTableChange"
        >
          <template slot="categorySlots" slot-scope="text">
            <span>{{ text.name }}</span>
          </template>
          <template slot="specType" slot-scope="text">
            <span>{{ text == '1' ? '单规格' : '多规格' }}</span>
          </template>
          <template slot="imgs" slot-scope="text">
            <div style="display: flex; flex-direction: row; align-items: center; justify-content: center">
              <a :href="imgUrl" target="_blank" v-for="(imgUrl, imgIndex) in text" :key="imgIndex">
                <img class="code-img" :src="imgUrl" alt="" />
              </a>
            </div>
          </template>
          <template slot="deductStockType" slot-scope="text">
            <span>{{ text == '1' ? '下单减库存' : '付款减库存' }}</span>
          </template>
          <template slot="goodsStatus" slot-scope="text">
            <span :style="{ color: text == 1 ? '#1890ff' : '#ff0000' }">{{ statusMap[text] }}</span>
          </template>
          <template slot="recommend" slot-scope="text">
            <span :style="{ color: text == 0 ? '#1890ff' : '#ff0000' }">{{ recommendMap[text] }}</span>
          </template>
          <template slot="modifyTime" slot-scope="text, record">
            <span>{{ text && text.length > 0 ? text : record.createTime }}</span>
          </template>
          <template slot="operation" slot-scope="text, record">
            <a-button type="link" @click="handleOperationClick('edit', record)" class="icon" >修改</a-button>
            <a-button
              v-if="record.goodsStatus == 2"
              type="link"
              class="icon"
              style="padding-left:10px"
              @click="onApproval(record.id, 1)"
            >上架</a-button>
            <a-button
              v-if="record.goodsStatus == 1"
              type="link"
              @click="onApproval(record.id, 2)"
              class="icon"
              style="padding-left:10px"
            >下架</a-button>
            <a-button
              type="link"
              @click="onDelete(record)"
              class="icon"
              style="padding-left:10px"
            >删除</a-button>
          </template>
        </a-table>
        <!-- 新增 -->
        <add-record
          :addOrEdit="addOrEdit"
          :key="addKey"
          :visible="addVisible"
          :initRecord="selectedRecord"
          :goodsCategorys="goodsCategorys"
          :goodsFreights="goodsFreights"
          @close="addVisible = false"
          @success="onAddSuccess"
          :apiURL="apiURL"
        ></add-record>
      </template>
    </layout-content>
  </div>
</template>

<script>
import db from 'utils/localstorage';
import columns from './columns';
import apiURL from './requestURL';
import searchView from './search-view';
import addRecord from './add';
import layoutContent from '@/components/tool/layout-content';

export default {
  name: 'mainPage',
  components: { searchView, addRecord, layoutContent },
  data() {
    return {
      // 添加或编辑
      addOrEdit: 0,
      // 组件渲染的key
      addKey: new Date().getTime(),
      params: {},
      columns,  // 表头字段
      apiURL, // 接口url
      // 组件的可见性
      addVisible: false,
      // 当前选中的记录
      selectedRecord: {},
      dataSource: [],
      sortedInfo: null,
      paginationInfo: null,
      pagination: {
        size: 'small',
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
      loading: false,
      statusMap: Object.freeze({
        '1': '上架',
        '2': '下架'
      }),
      recommendMap: Object.freeze({
        '0': '是',
        '1': '否'
      }),
      // 商品类别
      goodsCategorys: [],
      // 运费模版
      goodsFreights: []
    };
  },
  created() {
    this.getGoodsCategorys();
    this.getGoodsFreights();
    this.fetch();
  },
  mounted() {},
  methods: {
    // ------------------------- 界面交互事件 -------------------------
    handleOperationClick(key, record = {}) {
      this.addOrEdit = key === 'add' ? 0 : 1;
      if (this.addOrEdit) {
        record.imageList = record.images;
        record.specType = parseInt(record.specType);
        record.deductStockType = parseInt(record.deductStockType);
        record.goodsStatus = parseInt(record.goodsStatus);
        record.recommend = parseInt(record.recommend);
        record.deliveryId = parseInt(record.deliveryId);
        if (record.specType == 1) {
          record.goodsNo = record.goodsSpec.goodsNo;
          record.goodsPrice = record.goodsSpec.goodsPrice;
          record.linePrice = record.goodsSpec.linePrice;
          record.stockNum = record.goodsSpec.stockNum;
          record.goodsWeight = record.goodsSpec.goodsWeight;
        } else {
          let specDetailList = record.specDetailList;
          var specList = [];
          for (var i = 0; i < specDetailList.length; i++) {
            let item = specDetailList[i];
            let itemValues = item.specValueList;
            var objValues = [];
            for (var j = 0; j < itemValues.length; j++) {
              let itemValue = itemValues[j];
              let objValue = {
                createTime: "",
                id: itemValue.specValueId,
                specId: item.specId,
                specValue: itemValue.specValue,
                userId: ''
              };
              objValues.push(objValue);
            }
            let obj = {
              createTime: "",
              id: item.specId,
              specName: item.specName,
              specValueInput: "",
              userId: '',
              values: objValues
            };
            specList.push(obj);
          }
          record.specList = specList;
        }
      }
      if (this.addOrEdit == 0) {
        record.deliveryId = this.goodsFreights.length > 0 ? this.goodsFreights[0].id : '';
      }
      this.selectedRecord = record;
      this[`addKey`]++;
      this.addVisible = true;
    },
    /**
     * @desc: 新增成功时的回调函数，隐藏新增组件，提示，查询
     * @param {type}
     * @author: youzi
     */
    onAddSuccess() {
      this.addVisible = false;
      this.$message.success('操作成功');
      this.search(that.params);
      // this.search();
      // this.$refs['searchView'].handleSearch();
    },
    // 删除记录
    onDelete(record) {
      let that = this;
      this.$confirm({
        title: '确定删除吗?',
        content: '删除将不能恢复哦！',
        centered: true,
        onOk() {
          that.$post(apiURL.deleteRecord, { id: record.id }).then(() => {
            that.$message.success('删除成功');
            that.search(that.params);
          });
        },
        onCancel() {}
      });
    },
    onApproval (id, goodsStatus) {
      let that = this;
      let op = goodsStatus === 2 ? '下架': '上架'
      this.$confirm({
        title: '提示?',
        content: `确定${op}吗？`,
        centered: true,
        onOk() {
          that.$post(apiURL.changeGoodsStatus, { id, goodsStatus }).then(() => {
            that.$message.success(`${op}成功`);
            that.search(that.params);
          });
        },
        onCancel() {}
      });
    },
    // 分页信息改变时的回调
    handleTableChange(pagination, filters, sorter) {
      // 将这两个参数赋值给Vue data，用于后续使用
      this.paginationInfo = pagination;
      this.sortedInfo = sorter;
      this.fetch({
        ...this.params,
        sortField: sorter.field,
        sortOrder: sorter.order
      });
    },
    // 搜索
    search(params = {}) {
      this.params = params;
      let { sortedInfo } = this;
      let sortField, sortOrder;
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field;
        sortOrder = sortedInfo.order;
      }
      this.fetch({
        ...params,
        sortField: sortField,
        sortOrder: sortOrder
      });
    },

    // ------------------------- 网络请求 -------------------------
    // 1.查询记录
    fetch(params = {}) {
      this.loading = true;
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current;
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize;
        params.pageSize = this.paginationInfo.pageSize;
        params.pageNum = this.paginationInfo.current;
      } else {
        // 如果分页信息为空，则设置为默认值
        params.count = this.pagination.defaultPageSize;
        params.currentPage = this.pagination.defaultCurrent;
      }
      this.$post(apiURL.getRecords, {
        ...params
      }).then(r => {
        console.log(r);
        let data = r.data.data;
        let pagination = { ...this.pagination };
        pagination.total = data.total;
        var dataSource = [];
        for (var i = 0; i < data.rows.length; i++) {
          let item = data.rows[i];
          let images = item.images;
          var imageArr = images.split(',');
          item.images = imageArr;
          dataSource.push(item);
        }
        this.dataSource = dataSource;
        this.pagination = pagination;
        this.loading = false;
      }).catch(e => {
        console.error(e);
        this.loading = false;
      });
    },
    // 2.获取商品类别
    getGoodsCategorys() {
      this.$post(this.apiURL.getGoodsCategory, { pageSize: 1000, pageNum: 1 })
        .then(r => {
          this.goodsCategorys = r.data.data.rows;
        })
        .catch(e => {
          console.error(e);
        });
    },
    // 3.获取运费模版
    getGoodsFreights() {
      this.$post(this.apiURL.getGoodsFreight, { pageSize: 1000, pageNum: 1 })
        .then(r => {
          this.goodsFreights = r.data.data.rows;
        })
        .catch(e => {
          console.error(e);
        });
    },
  }
};
</script>

<style lang="less" scoped>
.code-img {
  width: 50px !important;
  margin: 10px 2px;
}
.icon {
  padding: 0;
  border: none;
  color: #1890ff;
}
.card-area {
  .extra-btn {
    width: 86px;
  }
}
.search-btn {
  margin-top: 8px;
}
.border-span {
  width: 2px;
  background-color: #cfd7de;
  height: 16px;
  margin-right: 2px;
  display: inline-block;
}
</style>
